import { useEffect, useState, forwardRef, useImperativeHandle } from 'react';
import { createPortal } from 'react-dom';
import { NavBar, SpinLoading, ErrorBlock, Dialog, PullToRefresh } from 'antd-mobile';
import { TextWidget, getMessage } from '@inbiz/react';
import { useApp } from '@inbiz/utils';
import { useTemplate } from '@inbiz/hooks';
import { useErrorBoundary } from 'use-error-boundary';
import { getTimeDisplayText, getText, exchangeVariable } from './utils';
import { getMessage as requestGetMessage, setReaded } from '../service';
import NoData from '../assets/noData.svg';
import './style.less';

const MessagePortal = forwardRef((props: any, ref) => {
    const { controlId, group, getGroups, setCurrentMessage, emit, callBackEvents } = props;
    const [loading, setLoading] = useState(true);
    const [data, setData] = useState([]);
    const appInfo = useApp();
    const localGroup = JSON.parse(localStorage.getItem(`${controlId}-message-h5-current-group`) || '');

    const getGroupMessages = async () => {
        setLoading(true);
        try {
            let result = await requestGetMessage({
                pageIndex: 1,
                pageSize: 999,
                readState: -1,
                group: [{ groupKey: group?.GroupKey || localGroup?.GroupKey || '', appId: group?.AppId || localGroup?.AppId || '' }]
            });
            setData(result?.Items);
            setLoading(false);
        } catch (error) {
            setLoading(false);
        }
    };

    useEffect(() => {
        getGroupMessages();
    }, [group]);

    const readAll = () => {
        if (loading) {
            return;
        };
        const _group = data?.map((item: any) => {
            return {
                groupKey: item?.Key || item?.GroupKey,
                appId: item?.AppId?.replaceAll('{AppId}', appInfo?.AppId),
            };
        }) || [];
        setLoading(true);
        setReaded({
            readAll: true,
            group: _group,
        })
            .then((res) => {
                if (res) {
                    getGroupMessages();
                };
            })
    };

    const right = data?.length && data?.some((item: { MsgRead: boolean }) => !item?.MsgRead) ? <div onClick={readAll}>
        <TextWidget>Message.tips.all_read</TextWidget>
    </div> : null;

    const back = () => {
        setData([]);
        getGroups();
        let _href = window.location.href;
        _href = _href?.replace('?portalType=list', '')
        window.history.pushState({}, '', `${_href}`);
    };

    const onListItemClick = (data: any) => {
        let _href = window.location.href;
        if (_href?.indexOf('portalType=detail') == -1) {
            _href = _href?.replace('portalType=list', 'portalType=detail')
            window.history.pushState({}, '', `${_href}`);
            localStorage.setItem(`${controlId}-message-h5-current-message`, JSON.stringify(data));
            setCurrentMessage(data);
            if (!data?.MsgRead) {
                setLoading(true);
                setReaded({
                    id: data?.Id
                })
                    .then((res) => {
                        if (res) {
                            getGroupMessages();
                        };
                    })
            }
        }
    };

    useImperativeHandle(ref, () => ({
        getGroupMessages,
    }));

    return (
        <div className='message-h5-message-portal-wrapper' style={{ height: document.body.clientHeight }}>
            <NavBar right={right} onBack={back}>
                {group?.GroupName || localGroup?.GroupName}
            </NavBar>
            <PullToRefresh
                onRefresh={async () => {
                    await getGroupMessages();
                }}
            >
                <div className='message-h5-message-portal-body'>
                    {
                        loading
                            ?
                            <div className='message-h5-message-portal-loading'>
                                <SpinLoading color='var(--inbiz-color-primary)' />
                            </div>
                            :
                            data?.length == 0
                                ?
                                <ErrorBlock
                                    image={NoData}
                                    description=''
                                    title={getMessage('Message.tips.noContent')}
                                />
                                :
                                data?.map((item: { Id: string; WapTemplatePath: string; WapMsgTitle: string; WapMsgContent: string; MsgTime: string; WapTemplateConfig: number }) => {
                                    if (item?.WapTemplateConfig == 1) {
                                        if (item?.WapTemplatePath) {
                                            return (
                                                <MessageTempListItem
                                                    key={item?.Id}
                                                    data={item}
                                                    emit={emit}
                                                    callBackEvents={callBackEvents}
                                                    onListItemClick={onListItemClick}
                                                />
                                            )
                                        } else {
                                            return (
                                                <MessageNoTemp
                                                    key={item?.Id}
                                                    data={item}
                                                    getGroupMessages={getGroupMessages}
                                                    setData={setData}
                                                />
                                            )
                                        }
                                    } else {
                                        if (!item?.WapMsgTitle && !item?.WapMsgContent) {
                                            return (
                                                <MessageNoTemp
                                                    key={item?.Id}
                                                    data={item}
                                                    getGroupMessages={getGroupMessages}
                                                    setData={setData}
                                                />
                                            )
                                        } else {
                                            return (
                                                <MessageRichListItem
                                                    key={item?.Id}
                                                    data={item}
                                                    emit={emit}
                                                    callBackEvents={callBackEvents}
                                                    onListItemClick={onListItemClick}
                                                />
                                            )
                                        }
                                    }
                                })
                    }
                </div>
            </PullToRefresh>
        </div>
    )
});

function MessageTempListItem(props: any) {
    const { data, emit, callBackEvents, onListItemClick } = props;
    const [Temp] = useTemplate(data.WapTemplatePath);
    const { ErrorBoundary, didCatch } = useErrorBoundary();

    return (
        <div
            className='message-h5-message-list-item'
            onClick={() => {
                if (didCatch) {
                    return;
                };
                onListItemClick(data);
            }}
        >
            {
                data.WapTemplatePath && data.WapTemplatePath?.trim() !== '' ?
                    Temp?.default ? <>
                        {
                            didCatch ? <div className='inbiz-message-template-error'>模板解析失败，请检查js语法</div> :
                                <ErrorBoundary>
                                    {/* @ts-ignore */}
                                    <Temp.default parameter={JSON.parse(data.Parameter)} record={data} emit={emit} callBackEvents={callBackEvents} type='list' />
                                </ErrorBoundary>
                        }
                    </> : null :
                    <div
                        dangerouslySetInnerHTML={{ __html: data.WapMsgContent }}
                    ></div>
            }
        </div>
    )
};

function MessageRichListItem(props: any) {
    const { data: { WapMsgTitle, MsgTime, MsgRead, WapMsgContent, Parameter }, onListItemClick } = props;

    return (
        <div
            className='message-h5-message-rich-item-wrapper'
            onClick={() => { onListItemClick(props.data) }}
        >
            <div className='message-h5-message-rich-item-title'>
                <div className='message-h5-message-rich-item-title-text'>
                    {WapMsgTitle}
                </div>
                <div className='message-h5-message-rich-item-title-time'>
                    {MsgTime ? getTimeDisplayText(MsgTime) : ''}
                </div>
            </div>
            <div className='message-h5-message-rich-item-content'>
                <div className='message-h5-message-rich-item-content-text'>
                    {exchangeVariable(getText(WapMsgContent), JSON.parse(Parameter))}
                </div>
                <div className='message-h5-message-rich-item-content-ifRead'>
                    {MsgRead === false && <div style={{ width: 8, height: 8, background: 'rgb(234, 77, 62)', borderRadius: 4 }} />}
                </div>
            </div>
        </div>
    )
};

function MessageNoTemp(props: { data: any; getGroupMessages: any; setData: any; }) {
    const { data: { MsgTime, Id, MsgRead }, setData } = props;

    const onNoTempClick = () => {
        if (!MsgRead) {
            setReaded({ id: Id }).then(() => {
                setData((pre: any[]) => {
                    let _pre = pre?.map((item: { Id: string; }) => {
                        if (item?.Id == Id) {
                            return {
                                ...item,
                                MsgRead: true,
                            }
                        } else {
                            return item;
                        }
                    });
                    return _pre;
                })
            });
        }
        Dialog.alert({
            content: getMessage('Message.tips.plzTemp'),
            closeOnMaskClick: true,
            bodyClassName: 'message-h5-message-noTemp-dialog',
        });
    };

    return (
        <div
            className='message-h5-message-noTemp-wrapper'
            onClick={onNoTempClick}
        >
            <div className='message-h5-message-noTemp-wrapper-text'>
                {getMessage('Message.tips.noTemp1')}
            </div>
            <div className='message-h5-message-noTemp-wrapper-text-time'>
                {MsgTime ? getTimeDisplayText(MsgTime) : ''}
            </div>
        </div>
    )
};

export default MessagePortal;